//
//  IOARequest.m
//  IOAMall
//
//  Created by Mac on 2018/1/31.
//  Copyright © 2018年 Mac. All rights reserved.
//

#import "IOARequest.h"

@interface IOARequest ()
@property (nonatomic, readwrite, assign) NSInteger serverResponseStatusCode;
@property (nonatomic, readwrite, assign) NSInteger serverRequestStatusCode;
@property (nonatomic, readwrite, copy) NSString *serverResponseMessage;

@end

@implementation IOARequest

// 设置请求超时时间
- (NSTimeInterval)requestTimeoutInterval {
    
    return 30.f;
}

// 设置请求方式 默认 POST
- (YTKRequestMethod)requestMethod {
    
    return YTKRequestMethodPOST;
}

- (void)startWithCompletionBlockWithSuccess:(YTKRequestCompletionBlock)success
                                    failure:(YTKRequestCompletionBlock)failure {
    
    if ([IOAApiManager getNetworkStatus] == 0) {
        self.serverResponseStatusCode = -1; // 没网络
        if (failure) {
            failure(self);
        }
        return;
    }
    
    WEAKSELF
    [self setCompletionBlockWithSuccess:success failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"statusCode: %ld\nresponse: %@\n\n%@", request.responseStatusCode ,request.responseObject, [request description]);
        if (weakSelf.serverRequestStatusCode == 0) { // 请求成功
            if (success) {
                success(request);
            }

        } else {
            
            // 登录过期
            if (weakSelf.serverRequestStatusCode == 1002) {
                [kNotificationCenter postNotificationName:WSTokenExpiredNotificationKey object:nil userInfo:nil];
            }
            if (failure) {
                failure(request);
            }
        }
    }];
     
    [self start];
}

- (BOOL)statusCodeValidator {
    // 判断响应状态码
    BOOL isOk = [super statusCodeValidator];
    if (!isOk) {
        NSLog(@"网络请求错误");
        return isOk;
    }
    
    if (!self.responseObject) {
        self.serverResponseStatusCode = -1;
        return NO;
    }

    self.serverResponseStatusCode = [self responseStatusCode];
    self.serverRequestStatusCode = [self.responseObject[@"error_code"] integerValue];
    self.serverResponseMessage = self.responseObject[@"msg"];
    
    return NO;
}

@end
